package com.bkgy.controller.qualityDaily.service.impl;

import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bkgy.controller.qualityDaily.entity.QualityAttr;
import com.bkgy.controller.qualityDaily.entity.QualityFan;
import com.bkgy.controller.qualityDaily.entity.QualityTuo;
import com.bkgy.controller.qualityDaily.entity.RepQuaMainData;
import com.bkgy.controller.qualityDaily.mapper.IQualitydailyMainDataMapper;
import com.bkgy.controller.qualityDaily.service.IQualityAttrService;
import com.bkgy.controller.qualityDaily.service.IQualityFanService;
import com.bkgy.controller.qualityDaily.service.IQualityTuoService;
import com.bkgy.controller.qualityDaily.service.IQualitydailyMainDataService;
import com.bkgy.controller.tPdiDataL3Cgl1870.entity.TPdiDataL3Cgl1870;
import com.bkgy.controller.tPdiDataL3Cgl1870.service.ITPdiDataL3Cgl1870Service;
import com.bkgy.controller.tPdiDataL3Tcm2280.entity.TPdiDataL3Tcm2280;
import com.bkgy.controller.tPdiDataL3Tcm2280.service.ITPdiDataL3Tcm2280Service;
import com.bkgy.controller.technology.entity.TDefectData;
import com.bkgy.controller.technology.service.ITDefectDataService;
import com.bkgy.controller.tpdol3data.entity.TPdoDataL3Cgl1870;
import com.bkgy.controller.tpdol3data.entity.TPdoDataL3Tcm2280;
import com.bkgy.controller.tpdol3data.service.ITPdoL3Cgl1870Service;
import com.bkgy.controller.tpdol3data.service.ITPdoL3Tcm2280Service;
import com.bkgy.sys.common.constant.CommonConstant;
import com.bkgy.sys.common.entity.ResultData;
import com.bkgy.util.DateUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service
@RequiredArgsConstructor
public class QualitydailyMainDataServiceImpl extends ServiceImpl<IQualitydailyMainDataMapper, RepQuaMainData>
        implements IQualitydailyMainDataService {
    private final ITDefectDataService defectService;
    private final ITPdiDataL3Tcm2280Service tcmPdiService;
    private final ITPdoL3Tcm2280Service tcmPdoService;
    private final ITPdiDataL3Cgl1870Service cglPdiService;
    private final ITPdoL3Cgl1870Service cglPdoService;
    private final IQualityTuoService tuoService;
    private final IQualityFanService fanService;
    private final IQualityAttrService attrService;

    @Override
    public ResultData<String> buildData(Date oneDay) {
        String beginDate = DateUtil.getDateToString(oneDay, "yyyyMMdd");
        //TODO
        beginDate = "2025-11-19";
        String endDate = DateUtil.getDateToString(DateUtil.getNextDayZero(oneDay), "yyyyMMdd");

        Map<String, List<QualityTuo>> map = new HashMap<>();
        map.put("酸轧生产", new ArrayList<>());
        map.put("酸轧设备", new ArrayList<>());
        map.put("2150连退生产", new ArrayList<>());
        map.put("2150连退设备", new ArrayList<>());
        map.put("1630连退生产", new ArrayList<>());
        map.put("1630连退设备", new ArrayList<>());
        map.put("镀锌生产", new ArrayList<>());
        map.put("镀锌设备", new ArrayList<>());
        map.put("磨辊", new ArrayList<>());
        map.put("公辅", new ArrayList<>());
        map.put("运转", new ArrayList<>());
        map.put("其它", new ArrayList<>());

        List<QualityAttr> list = attrService.list();
        Map<String, String> attrMap = new HashMap<>();
        for (QualityAttr qa : list) {
            attrMap.put(qa.getCol1(), qa.getCol2());
        }

        //分析脱合同表
        LambdaQueryWrapper<QualityTuo> w = new LambdaQueryWrapper<>();
        w.ge(QualityTuo::getCreateTime, beginDate).lt(QualityTuo::getCreateTime, endDate);
        List<QualityTuo> tuoList = tuoService.list(w);
        for (QualityTuo tuo : tuoList) {
            String guihu = tuo.getGuihu();
            String guihu2 = guihu.substring(guihu.indexOf("_") + 1);
            if(attrMap.containsKey(guihu2)){
                String key = attrMap.get(guihu2);
                if(map.containsKey(key)){
                    map.get(key).add(tuo);
                }else{
                    map.get("其它").add(tuo);
                }
            }else{
                map.get("其它").add(tuo);
            }
        }
        System.out.println("======脱合同======");
        for(Map.Entry<String,List<QualityTuo>> entry:map.entrySet()){
            System.out.println(entry.getKey()+"-"+entry.getValue());
        }

        Map<String, List<QualityFan>> map2 = new HashMap<>();
        map2.put("酸轧生产", new ArrayList<>());
        map2.put("酸轧设备", new ArrayList<>());
        map2.put("2150连退生产", new ArrayList<>());
        map2.put("2150连退设备", new ArrayList<>());
        map2.put("1630连退生产", new ArrayList<>());
        map2.put("1630连退设备", new ArrayList<>());
        map2.put("镀锌生产", new ArrayList<>());
        map2.put("镀锌设备", new ArrayList<>());
        map2.put("磨辊", new ArrayList<>());
        map2.put("公辅", new ArrayList<>());
        map2.put("运转", new ArrayList<>());
        map2.put("其它", new ArrayList<>());
        //分析返工表
        LambdaQueryWrapper<QualityFan> w2 = new LambdaQueryWrapper<>();
        w2.ge(QualityFan::getCreateTime, beginDate).lt(QualityFan::getCreateTime, endDate);
        List<QualityFan> fanList = fanService.list(w2);
        for (QualityFan qf : fanList) {
            String guihu = qf.getGuihu();
            String guihu2 = guihu.substring(guihu.indexOf("_") + 1);
            if(attrMap.containsKey(guihu2)){
                String key = attrMap.get(guihu2);
                if(map2.containsKey(key)){
                    map2.get(key).add(qf);
                }else{
                    map2.get("其它").add(qf);
                }
            }else{
                map2.get("其它").add(qf);
            }
        }

        System.out.println("======返工======");
        for(Map.Entry<String,List<QualityFan>> entry:map2.entrySet()){
            System.out.println(entry.getKey()+"-"+entry.getValue());
        }

        return ResultData.ResultDataSuccess("SUCCESS");
    }

    public ResultData<String> buildData_old(Date oneDay) {
        String beginDate = DateUtil.getDateToString(oneDay, "yyyyMMdd");
        String endDate = DateUtil.getDateToString(DateUtil.getNextDayZero(oneDay), "yyyyMMdd");

        RepQuaMainData mainData = new RepQuaMainData();
        mainData.setShijian(beginDate);
        //构建酸轧部分数据
        buidTcm(mainData, beginDate, endDate);
        //构建连退2150部分数据
        buildCal2150(mainData, beginDate, endDate);
        //构建连退1630部分数据
        buildCal1630(mainData, beginDate, endDate);
        //构建镀锌1870部分数据
        buildCgl(mainData, beginDate, endDate);
        //分析重卷

        saveOrUpdate(mainData);
        return ResultData.ResultDataSuccess("SUCCESS");
    }

    private void buildCgl(RepQuaMainData mainData, String dateBegin, String dateEnd) {
        //查询PDO数据
        LambdaQueryWrapper<TPdoDataL3Cgl1870> w1 = new LambdaQueryWrapper<>();
        w1.ge(TPdoDataL3Cgl1870::getProdEndTime, dateBegin).lt(TPdoDataL3Cgl1870::getProdEndTime, dateEnd);
        List<TPdoDataL3Cgl1870> pdoList = cglPdoService.list(w1);
        if (pdoList.size() == 0) return;
        //卷号与出口重量
        Map<String, TPdoDataL3Cgl1870> cglMap = new HashMap<>();
        List<String> entIdList = new ArrayList<>();
        BigDecimal sumOutputWt = BigDecimal.ZERO;
        for (TPdoDataL3Cgl1870 item : pdoList) {
            sumOutputWt = sumOutputWt.add(item.getOutMatWt());
            cglMap.put(item.getExtid(), item);
            entIdList.add(item.getEntid());
        }

        //根据出口卷号查询缺陷
        LambdaQueryWrapper<TDefectData> w2 = new LambdaQueryWrapper<>();
        w2.in(TDefectData::getExtId, cglMap.keySet()).orderByAsc(TDefectData::getDefectVersionTime1);
        List<TDefectData> defectList = defectService.list(w2);
        Map<String, TDefectData> defectMap = new HashMap<>();
        for (TDefectData item : defectList) {
            defectMap.put(item.getExtId(), item);
        }

        //从pdi中获取表面等级
        LambdaQueryWrapper<TPdiDataL3Cgl1870> w3 = new LambdaQueryWrapper<>();
        w3.select(TPdiDataL3Cgl1870::getSurfaceCode, TPdiDataL3Cgl1870::getEntid);
        w3.in(TPdiDataL3Cgl1870::getEntid, entIdList);
        Map<String, String> pdiMap = new HashMap<>();
        List<TPdiDataL3Cgl1870> pdiList = cglPdiService.list(w3);
        for (TPdiDataL3Cgl1870 item : pdiList) {
            pdiMap.put(item.getEntid(), item.getSurfaceCode());
        }

        //组合数据
        BigDecimal sumFeicijiang = BigDecimal.ZERO;//废次降总重
        for (Map.Entry<String, TPdoDataL3Cgl1870> entry : cglMap.entrySet()) {
            String extId = entry.getKey();
            TPdoDataL3Cgl1870 pdo = entry.getValue();
            String entId = pdo.getEntid();
            //求废次降
            int surFaceCode = Integer.parseInt(pdiMap.get(entId));//要求表面等级代码
            int actSurFaceCode = surFaceCode;
            if (StringUtils.isNumeric(pdo.getSurfaceAccuClassCode())) {
                actSurFaceCode = Integer.parseInt(pdo.getSurfaceAccuClassCode());
            }

            if (surFaceCode > actSurFaceCode) {
                sumFeicijiang = sumFeicijiang.add(pdo.getOutMatWt());

                //求缺陷、封闭归户
                if (defectMap.containsKey(extId)) {
                    TDefectData defect = defectMap.get(extId);
                    //查看归户
                    String unitCode = defect.getUnitCode();
                    String guihu = CommonConstant.tPdi1870HomeMap.get(defect.getDefectAttributionCode1());
                    if (guihu != null) {
                        String comment = defect.getDefectComment1();
                        //封闭量
                        BigDecimal fengbi = BigDecimal.ZERO;
                        BigDecimal feici = pdo.getOutMatWt();
                        if (comment != null && comment.contains("封闭") && comment.indexOf("封闭") < 5) {
                            fengbi = pdo.getOutMatWt();
                        }

                        if (guihu.contains("磨辊")) {
                            mainData.setCol60(mainData.getCol60().add(feici));
                            mainData.setCol61(mainData.getCol61().add(fengbi));
                        } else if (guihu.contains("公辅")) {
                            mainData.setCol70(mainData.getCol70().add(feici));
                            mainData.setCol71(mainData.getCol71().add(fengbi));
                        } else if (guihu.contains("运转")) {
                            mainData.setCol80(mainData.getCol80().add(feici));
                            mainData.setCol81(mainData.getCol81().add(fengbi));
                        } else if (guihu.contains("机械") || guihu.contains("电气")) {
                            //根据产线编码将废次重归集到不同产线
                            if ("L611".equals(unitCode)) {//酸轧
                                mainData.setCol10(mainData.getCol10().add(feici));
                                mainData.setCol11(mainData.getCol11().add(fengbi));
                            } else if ("L612".equals(unitCode) || "L613".equals(unitCode)) {//连退
                                mainData.setCol30(mainData.getCol30().add(feici));
                                mainData.setCol31(mainData.getCol31().add(fengbi));
                            } else {//镀锌
                                mainData.setCol50(mainData.getCol50().add(feici));
                                mainData.setCol51(mainData.getCol51().add(fengbi));
                            }
                        } else {
                            if ("L611".equals(unitCode)) {//酸轧
                                mainData.setCol00(mainData.getCol00().add(feici));
                                mainData.setCol01(mainData.getCol01().add(fengbi));
                            } else if ("L612".equals(unitCode) || "L613".equals(unitCode)) {
                                mainData.setCol20(mainData.getCol20().add(feici));
                                mainData.setCol21(mainData.getCol21().add(fengbi));
                            } else {
                                mainData.setCol40(mainData.getCol40().add(feici));
                                mainData.setCol41(mainData.getCol41().add(fengbi));
                            }
                        }
                    }
                }
            }
        }
        //镀锌
        mainData.setOutputWt4(sumOutputWt);
        mainData.setFeicijiang4(sumFeicijiang);
    }

    private void buildCal1630(RepQuaMainData mainData, String dateBegin, String dateEnd) {
        //TODO
    }

    private void buildCal2150(RepQuaMainData mainData, String dateBegin, String dateEnd) {
        //TODO
    }

    private void buidTcm(RepQuaMainData mainData, String dateBegin, String dateEnd) {
        //查询PDO数据，入口卷号、出口卷号、出口产量
        LambdaQueryWrapper<TPdoDataL3Tcm2280> w1 = new LambdaQueryWrapper<>();
        w1.select(TPdoDataL3Tcm2280::getEntid, TPdoDataL3Tcm2280::getExtid, TPdoDataL3Tcm2280::getOutMatWt);
        w1.ge(TPdoDataL3Tcm2280::getProdEndTime, dateBegin).lt(TPdoDataL3Tcm2280::getProdEndTime, dateEnd);
        List<TPdoDataL3Tcm2280> pdoList = tcmPdoService.list(w1);
        if (pdoList.size() == 0) return;
        //出口卷号与记录
        Map<String, TPdoDataL3Tcm2280> extIdMap = new HashMap<>();
        List<String> entIdList = new ArrayList<>();
        BigDecimal sumOutputWt = BigDecimal.ZERO;
        for (TPdoDataL3Tcm2280 item : pdoList) {
            sumOutputWt = sumOutputWt.add(item.getOutMatWt());
            extIdMap.put(item.getExtid(), item);
            entIdList.add(item.getEntid());
        }

        //根据出口卷号查询缺陷。出口卷号与缺陷记录
        Map<String, TDefectData> defectMap = new HashMap<>();
        LambdaQueryWrapper<TDefectData> w2 = new LambdaQueryWrapper<>();
        w2.ne(TDefectData::getDefectClass1, "0");//0认为是正常
        w2.in(TDefectData::getExtId, extIdMap.keySet()).orderByAsc(TDefectData::getDefectVersionTime1);
        List<TDefectData> defectList = defectService.list(w2);
        for (TDefectData item : defectList) {
            defectMap.put(item.getExtId(), item);
        }

        //从pdi中获取表面等级，COATING_TYPE，入口卷号
        Map<String, String> entIdCoatingTypeMap = new HashMap<>();
        LambdaQueryWrapper<TPdiDataL3Tcm2280> w3 = new LambdaQueryWrapper<>();
        w3.select(TPdiDataL3Tcm2280::getCoatingType, TPdiDataL3Tcm2280::getEntid);
        w3.in(TPdiDataL3Tcm2280::getEntid, entIdList);
        List<TPdiDataL3Tcm2280> tcmPdiList = tcmPdiService.list(w3);
        for (TPdiDataL3Tcm2280 item : tcmPdiList) {
            entIdCoatingTypeMap.put(item.getEntid(), item.getCoatingType());
        }

        //组合数据
        BigDecimal sumFeicijiang = BigDecimal.ZERO;//废次降总重
        for (Map.Entry<String, TPdoDataL3Tcm2280> entry : extIdMap.entrySet()) {
            String extId = entry.getKey();
            TPdoDataL3Tcm2280 pdo = entry.getValue();
            String entId = pdo.getEntid();
            if (defectMap.containsKey(extId)) {
                TDefectData defect = defectMap.get(extId);
                if (defect.getDefectClass1() == null) continue;
                //要求表面等级代码
                int coatingType = Integer.parseInt(entIdCoatingTypeMap.get(entId));
                int actSurface = coatingType;

                if (StringUtils.isNumeric(defect.getDefectClass1())) {
                    actSurface = Integer.parseInt(defect.getDefectClass1());
                }
                //判断废品、次材、降级：pdi中的coating_type与缺陷代码中的表面等级对比
                if (coatingType > actSurface) {
                    BigDecimal feici = pdo.getOutMatWt();
                    sumFeicijiang = sumFeicijiang.add(feici);

                    //查看归户
                    String guihu = CommonConstant.tPdi1870HomeMap.get(defect.getDefectAttributionCode1());
                    if (guihu != null) {
                        if (guihu.contains("磨辊")) {
                            mainData.setCol60(mainData.getCol60().add(feici));
                        } else if (guihu.contains("公辅")) {
                            mainData.setCol70(mainData.getCol70().add(feici));
                        } else if (guihu.contains("运转")) {
                            mainData.setCol80(mainData.getCol80().add(feici));
                        } else if (guihu.contains("机械") || guihu.contains("电气")) {
                            mainData.setCol10(mainData.getCol10().add(feici));
                        } else {
                            mainData.setCol00(mainData.getCol00().add(feici));
                        }
                    }
                }
            }
        }
        //酸轧不计算封闭量
        mainData.setOutputWt0(sumOutputWt);
        mainData.setFeicijiang0(sumFeicijiang);
    }
}
